package admin.controllers;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.forms.SubmitSiteForm;
import admin.models.SubmitSiteModel;

import entities.SubmitSite;


@SuppressWarnings("serial")
public class SubmitSiteEditServlet extends HttpServlet 	{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/submitsite/list");
			return;
		}
		
		SubmitSiteModel submitSiteModel = SubmitSiteModel.getInstance();
		SubmitSite submitSite = submitSiteModel.get(id);
		
		if (submitSite == null) {
			response.sendRedirect("/admin/submitsite/list");
			return;
		}
		
		
		request.setAttribute("check", check);
		request.setAttribute("submitSite", submitSite);
		try {
			request.getRequestDispatcher("/admin/pages/submit_site_form.jsp").forward(request, response);
		} catch (ServletException e) {
			//
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/submitsite/list");
			return;
		}
		
		SubmitSiteModel submitSiteModel = SubmitSiteModel.getInstance();
		SubmitSite submitSite = submitSiteModel.get(id);
		
		if (submitSite == null) {
			response.sendRedirect("/admin/submitsite/list");
			return;
		}
		
		TreeMap<String, Object> form = SubmitSiteForm.checkValid(request, submitSite);
		submitSite = (SubmitSite) form.get("submitSite");
		check = (TreeMap<String, String>) form.get("checkValid");
		
		if (check.size() == 0) {
			submitSiteModel.insert(submitSite);
			
			request.setAttribute("success", "Update success submit site with url " + submitSite.getSiteUrl());
		}
		
		request.setAttribute("check", check);
		request.setAttribute("submitSite", submitSite);
		try {
			request.getRequestDispatcher("/admin/pages/submit_site_form.jsp").forward(request, response);
		} catch (ServletException e) {
			//
		}
	}
}
